/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import Memmory.Word;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author Andrius
 */
public class Console {
    private GUI guiObj;
    private String text;
    private boolean textEntered = false;
    public boolean mustRestart = false;

    public Console(GUI gui) {
        guiObj = gui;
        guiObj.input.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                text = guiObj.input.getText();
                textEntered = true;
            }
        });
    }
    
    public void putTextToConsole(String text) {
        guiObj.consolePane.setText(guiObj.consolePane.getText() + text);
    }
    
    public void clearConsole() {
        guiObj.consolePane.setText("");
    }
    
    public byte[] getBytesFromConsole() throws Exception {
        while (!textEntered) {
            Thread.sleep(1); 
            if (mustRestart) {
                text = "";
                mustRestart = false;
                guiObj.input.setText("");
                break;
            }
        }
        
        byte[] textBytes = null;
        
        if (text.startsWith("'") && text.endsWith("'")) {
            text = text.replaceAll("'", "");
            
            int inputLength = text.getBytes().length;
            int size = inputLength + 1;

            int x = 4 - size % 4;
            if (x != 4) {
                size += x;
            }

            textBytes = new byte[size];
            System.arraycopy(text.getBytes(), 0, textBytes, 0, text.getBytes().length);

            for (int i = inputLength; i < size; i++) {
                textBytes[i] = '$';
            }
        } else {
            Word word = new Word(Integer.parseInt(text));
            textBytes = word.getBytes();
        }
        
        textEntered = false;
        guiObj.input.setText("");
        this.putTextToConsole(this.text + "\n");
        
        return textBytes;
    }
}
